<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="物流商">
              <j-search-select-tag placeholder="请输入物流商" v-model="queryParam.providerId" dict="hz_logistics_provider,name,id,logistics"></j-search-select-tag>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="物流渠道">
              <j-search-select-tag ref="searchSelectTagRef" placeholder="请输入物流渠道" v-model="queryParam.channelId" :filterOption_="false" @handleSearch="handleSearch"></j-search-select-tag>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="成本价方案">
              <a-input placeholder="请输入成本价方案" v-model.trim="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="状态">
                <j-dict-select-tag placeholder="请选择状态" v-model="queryParam.ableStatus" dict-code="able_status"/>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" v-has="'logisticsCostPrice:add'" type="primary" icon="plus">创建成本价</a-button>
      <a-button type="primary" @click="changeEnable('2', selectionRows,1)" v-has="'logisticsCostPrice:enable'">批量启用</a-button>
      <a-button type="primary" @click="changeEnable('3', selectionRows,1)" v-has="'logisticsCostPrice:enable'">批量禁用</a-button>
      <!-- <a-button type="primary" icon="download" @click="handleExportXls('物流成本价维护')">导出</a-button> -->
      <!-- <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload> -->
      <!-- 高级查询区域 -->
      <!-- <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query> -->
      <!-- <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown> -->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        class="j-table-force-nowrap"
        :scroll="{x:true}"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

         <!-- 生效时间 -->
         <template slot="effectTimeSlot" slot-scope="text,record">
          <div class="templateSlot">
            <div v-if="record.effectBeginTime">
              <span>起：</span>
              <span>{{record.effectBeginTime}}</span>
            </div>
            <div v-if="record.effectEndTime">
              <span>止：</span>
              <span>{{record.effectEndTime}}</span>
            </div>
          </div>
        </template>

        <!-- 状态 -->
        <template slot="ableStatusSlot" slot-scope="text,record">
          <span :style="{color: getColor(record)}">{{text}}</span>
        </template>

        <!-- 日期 -->
        <template slot="timeSlot" slot-scope="text,record">
          <div class="templateSlot">
            <div v-if="record.createTime">
              <span>创建日期：</span>
              <span>{{record.createTime}} {{record.createBy}}</span>
            </div>
            <div v-if="record.updateTime">
              <span>更新日期：</span>
              <span>{{record.updateTime}} {{record.updateBy}}</span>
            </div>
          </div>
        </template>

        <span slot="action" slot-scope="text, record">
          <!-- 启用状态禁止编辑 -->
          <a v-has="'logisticsCostPrice:edit'" @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" v-has="'logisticsCostPrice:edit'" />
          <!-- 草稿、禁用可以启用 -->
          <a v-has="'logisticsCostPrice:enable'" v-if="record.ableStatus === '1' || record.ableStatus === '3'" @click="changeEnable('2',record,2)">启用</a>
          <!-- 启用状态可以禁用 -->
          <a v-has="'logisticsCostPrice:enable'" v-if="record.ableStatus === '2'" style="color: red;" @click="changeEnable('3',record,2)">禁用</a>
          <a-divider type="vertical" v-has="'logisticsCostPrice:enable'" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <!-- 草稿状态无变更报价、历史报价 -->
              <a-menu-item v-has="'logisticsCostPrice:changePrice'" v-if="record.ableStatus != '1'" >
                <a @click="handleChangeOffer(record)" >变更报价</a>
              </a-menu-item>
              <a-menu-item v-has="'logisticsCostPrice:history'" v-if="record.ableStatus != '1'" >
                <a @click="handleHistoricalQuotation(record)" >历史报价</a>
              </a-menu-item>
              <!-- <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item> -->
              <!-- 操作日志 -->
              <a-menu-item>
                <j-operate-log :id="record.id"></j-operate-log>
              </a-menu-item>
              <a-menu-item v-has="'logisticsProduct:del'">
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a >删除 </a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>

    <logistics-cost-price-modal ref="modalForm" @ok="modalFormOk"/>
    <!-- 变更报价 -->
    <logistics-change-quotation-modal ref="modalChangeForm" @ok="modalFormOk" />
    <!-- 历史报价 -->
    <logistics-history-quotation-modal ref="modalHistoryForm" @ok="modalFormOk" />
  </a-card>
</template>

<script>

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import LogisticsCostPriceModal from './modules/LogisticsCostPriceModal'
  import LogisticsChangeQuotationModal from './modules/LogisticsChangeQuotationModal'
  import LogisticsHistoryQuotationModal from './modules/LogisticsHistoryQuotationModal'
  import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
  import '@/assets/less/TableExpand.less'
  import { getAction, postFormAction } from '@api/manage'
  import { simpleDebounce } from '@/utils/util'

  export default {
    name: "LogisticsCostPriceList",
    mixins:[JeecgListMixin],
    components: {
      LogisticsCostPriceModal,
      LogisticsChangeQuotationModal,
      LogisticsHistoryQuotationModal
    },
    data () {
      return {
        description: '物流成本价维护管理页面',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'成本价方案',
            align:"center",
            dataIndex: 'name'
          },
          // {
          //   title:'渠道id',
          //   align:"center",
          //   dataIndex: 'channelNo'
          // },
          {
            title:'物流商',
            align:"center",
            dataIndex: 'providerName'
          },
          {
            title:'渠道名称',
            align:"center",
            dataIndex: 'channelName'
          },
          {
            title:'计算方式',
            align:"center",
            dataIndex: 'calculateMethod_dictText'
          },
          {
            title:'报价版本',
            align:"center",
            dataIndex: 'version'
          },
          // {
          //   title:'重量段方案',
          //   align:"center",
          //   dataIndex: 'weightRangeId_dictText'
          // },
          // {
          //   title:'分区方案',
          //   align:"center",
          //   dataIndex: 'partitionId_dictText'
          // },
          {
            title:'报价生效时间',
            align:"center",
            dataIndex: 'effectTime',
            scopedSlots: { customRender: 'effectTimeSlot' }
          },
          {
            title:'状态',
            align:"center",
            dataIndex: 'ableStatus_dictText',
            scopedSlots: { customRender: 'ableStatusSlot' }
          },
          {
            title:'日期',
            align:"center",
            dataIndex: 'time',
            scopedSlots: { customRender: 'timeSlot' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' },
          }
        ],
        url: {
          list: "/logistics/costPrice/logisticsCostPrice/list",
          delete: "/logistics/costPrice/logisticsCostPrice/delete",
          deleteBatch: "/logistics/costPrice/logisticsCostPrice/deleteBatch",
          exportXlsUrl: "/logistics/costPrice/logisticsCostPrice/exportXls",
          importExcelUrl: "logistics/costPrice/logisticsCostPrice/importExcel",
          queryNameOrCodeChannel: "/logistics/channel/queryNameOrCode"
        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
      this.getSuperFieldList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    watch: {
      'queryParam.channelId': {
        immediate: true,
        handler(val){
          if(!val){
            this.handleSearch('');
          }
        }
      },
    },
    methods: {
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
         fieldList.push({type:'sel_search',value:'channelNo',text:'渠道id',dictTable:'hz_logistics_channel', dictText:'channel_name', dictCode:'channel_no'})
         fieldList.push({type:'sel_search',value:'providerId',text:'物流商',dictTable:'hz_logistics_provider', dictText:'name', dictCode:'id'})
         fieldList.push({type:'string',value:'calculatMethod',text:'计算方式',dictCode:'logistics_calculat_method'})
         fieldList.push({type:'sel_search',value:'weightRangeId',text:'重量段方案',dictTable:'hz_logistics_weight_range', dictText:'name', dictCode:'id'})
         fieldList.push({type:'sel_search',value:'partitionId',text:'分区方案',dictTable:'hz_logistics_partition', dictText:'name', dictCode:'id'})
         fieldList.push({type:'date',value:'effectBeginTime',text:'生效开始时间'})
         fieldList.push({type:'date',value:'effectEndTime',text:'生效结束时间'})
        this.superFieldList = fieldList
      },
      handleSearch: simpleDebounce(function(likeParam){
        getAction(this.url.queryNameOrCodeChannel, { likeParam: likeParam.trim() }).then((res) => {
          if(res.success){
            let dictOptions = res.result && res.result.map(item => {
              return {
                value: item.id,
                text: item.channelName
              }
            })
            this.$refs.searchSelectTagRef.setCurrentDictOptions(dictOptions);
          }else{
            this.$message.warning(res.message);
          }
        })
      }, 200),
      //操作启用禁用
      changeEnable(checked,records,type){
        const that = this
        if(!records || (Object.keys(records).length) === 0){
          this.$message.warning('请选择数据!');
          return;
        }

        let codes = "";
        if(type === 1){
          //批量操作
          codes = records.map(item => item.code).join(",");
        }else if(type === 2){
          //单个操作
          codes = records.code;
        }

        if(checked === '3'){
          that.$confirm({
            title:'渠道禁用',
            content: (
              <div>
                <div style="color: red">渠道禁用后关联产品将不可选</div>
                <div>你还要继续吗？</div>
              </div>
            ),
            okText: '继 续',
            onOk() {
              that.handlePost(checked,codes);
            },
            onCancel() {  },
          });
        }else{
          that.handlePost(checked,codes);
        }
      },
      handlePost(checked,record){
        postFormAction('/logistics/costPrice/logisticsCostPrice/changeEnable/', {isEnable: checked, codes: record})
          .then((res)=>{
            if(res.success){
              this.$message.success(res.message)
              this.loadData();
              this.selectedRowKeys = [];
            }else{
              this.$message.warning(res.message)
            }
          })
      },
      getColor(record){
        if(record.ableStatus === '1'){
          //草稿
          return '#ccc';
        }else if(record.ableStatus === '2'){
          //启用
          return '#67c23a';
        }else if(record.ableStatus === '3'){
          //禁用
          return 'red';
        }
      },
      handleChangeOffer(record){
        this.$refs.modalChangeForm.edit(record);
        this.$refs.modalChangeForm.title = "变更报价";
        this.$refs.modalChangeForm.disableSubmit = false;
      },
      handleHistoricalQuotation(record){
        this.$refs.modalHistoryForm.edit(record);
        this.$refs.modalHistoryForm.title = "历史报价";
        this.$refs.modalHistoryForm.disableSubmit = true;
      },
      handleEdit(record){
        this.$refs.modalForm.edit(record);
        this.$refs.modalForm.title = "编辑";
        // 启用状态禁止编辑
        this.$refs.modalForm.disableSubmit = record.ableStatus != '2' ? false : true;
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
  /deep/.ant-form{
    pointer-events: auto;
    cursor: auto;
  }
</style>